package com.wesley.netty.unpackage;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * UnpkgClientHandler
 *
 * @author WangPanYong
 * @since 2021/11/16 11:24
 */
public class UnpkgClientHandler extends SimpleChannelInboundHandler<CustomMessageProtocol> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CustomMessageProtocol msg) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for(int i = 0; i< 2; i++) {
            String msg = "你好，我是 Wesley！";
            // 创建协议包对象
            CustomMessageProtocol messageProtocol = new CustomMessageProtocol();
            messageProtocol.setLen(msg.getBytes(CharsetUtil.UTF_8).length);
            messageProtocol.setContent(msg.getBytes(CharsetUtil.UTF_8));
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
